package com.rockcent.api.utils;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author 李纪钢 keegan704@qq.com
 * @version 1.0 创建时间：14/11/12
 */
public class ResponseUtil {

    // 从response中获取json数据并封装成JSON对象
    public static JSONObject transToJson(HttpResponse response) throws IOException, JSONException {
        HttpEntity resEntity = response.getEntity();

        InputStream is = resEntity.getContent();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bReader.readLine()) != null) {
            sb.append(line);
        }

        Log.d("HTTP RESPONSE", sb.toString());
        return new JSONObject(sb.toString());
    }

    // 封装返回信息
    public static <T> T specialPackageMsg(HttpResponse response, TypeToken<T> typeToken)
            throws IOException, JSONException, JsonParseException {
        JSONObject json = transToJson(response);
        Gson gson = new Gson();
        String jsonString = json.toString();
        return gson.fromJson(jsonString, typeToken.getType());
    }

}
